import {Body, Controller, HttpStatus, Post, Get, Res, Query} from '@nestjs/common';
import {Response} from 'express';
import {CommonResponseDto} from '../../dto/common.response.dto';
import {ApplyDeviceStatus, ResCode} from '../../common/constants';
import {ApplyDeviceService} from "../../service/apply.device.service";
import {ApplyDeviceDto} from "../../dto/apply.device.dto";


@Controller('apply-admin/device')
export class ApplyDeviceController{
    constructor(private readonly applyDeviceService: ApplyDeviceService) {
    }

    @Post('/add')
    async addDevice(@Body() deviceDto: ApplyDeviceDto, @Res({ passthrough: true }) res: Response) {
        res.status(HttpStatus.OK);
        if (!deviceDto.deviceSn || !deviceDto.deviceType || !deviceDto.deviceName || !deviceDto.deviceAddress) {
            return new CommonResponseDto(ResCode.ERROR, 'deviceSn deviceType deviceName deviceAddress 必填', null)
        }
        try {
            const device  = await this.applyDeviceService.getOneBySn(deviceDto.deviceSn)
            if (device) {
                return new CommonResponseDto(ResCode.ERROR, 'deviceSn已存在', null)
            }
            deviceDto.status = ApplyDeviceStatus.NORMAL
            const result = await this.applyDeviceService.createOne(deviceDto)
            return new CommonResponseDto(ResCode.OK, '成功', result)
        } catch(e){
            console.log(e)
            return new CommonResponseDto(ResCode.ERROR, '服务异常', null)
        }
    }

    @Post('/edit')
    async editDevice(@Body() deviceDto: ApplyDeviceDto, @Res({ passthrough: true }) res: Response) {
        res.status(HttpStatus.OK);
        if (!deviceDto.deviceSn || !deviceDto.deviceType || !deviceDto.deviceName || !deviceDto.deviceAddress) {
            return new CommonResponseDto(ResCode.ERROR, 'deviceSn deviceType deviceName deviceAddress 必填', null)
        }
        try {
            if (![ApplyDeviceStatus.NORMAL, ApplyDeviceStatus.FORBIDDEN, ApplyDeviceStatus.DELETED].includes(deviceDto.status)) {
                return new CommonResponseDto(ResCode.ERROR, 'status状态不正确', null)
            }
            const result = await this.applyDeviceService.editOne(deviceDto)
            return new CommonResponseDto(ResCode.OK, '成功', result)
        } catch(e){
            console.log(e)
            return new CommonResponseDto(ResCode.ERROR, '服务异常', null)
        }
    }

    @Get('/list')
    async getAllDeviceList(@Query() query: {status?: ApplyDeviceStatus}, @Res({ passthrough: true }) res: Response) {
        console.log('getAllDeviceList', query)
        res.status(HttpStatus.OK);
        try {
            const result = await this.applyDeviceService.getAll(query.status)
            return new CommonResponseDto(ResCode.OK, '成功', result)
        } catch(e){
            console.log(e)
            return new CommonResponseDto(ResCode.ERROR, '服务异常', null)
        }
    }
}
